package com.jiliason.segmentation.repository.localcache.impl;

import com.jiliason.segmentation.constant.enums.Regex;
import com.jiliason.segmentation.constant.enums.TypeCategory;
import com.jiliason.segmentation.entity.mySql.TypesCstCachePojo;
import com.jiliason.segmentation.repository.mySql.ParseRepository;
import lombok.Getter;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;

@Component
public class TypesConstantCache {

    @Resource
    private ParseRepository parseRepository;

    @Getter
    private final TypesCstCachePojo cache = new TypesCstCachePojo();

    public void load() {
        loadDBToCache();
        constructDynamicRegex();
    }

    private void loadDBToCache() {
        // 省份类型list
        cache.setProvTypes(lenReversed(parseRepository.getTypesFromCategory(TypeCategory.tc1.v())));
        // 城市类型list
        cache.setCityTypes(lenReversed(parseRepository.getTypesFromCategory(TypeCategory.tc2.v())));
        // 区县类型list
        cache.setDistTypes(lenReversed(parseRepository.getTypesFromCategory(TypeCategory.tc3.v())));
        // 乡镇类型list
        cache.setTownTypes(lenReversed(parseRepository.getTypesFromCategory(TypeCategory.tc4.v())));
        // 路类型list ※路类型和POI名称类型必须不能有交集！
        cache.setRoadTypes(lenReversed(parseRepository.getTypesFromCategory(TypeCategory.tc5.v())));
        // POI名称类型list ※路类型和POI名称类型必须不能有交集！
        cache.setPoiStrTypes(lenReversed(parseRepository.getTypesFromCategory(TypeCategory.tc7.v())));
        // 门牌号等详细信息的类型list
        cache.setRpDetailTypes(lenReversed(parseRepository.getTypesFromCategory(TypeCategory.tc8.v())));

        // detailBranch类型
        cache.setDetailBranchTypes(lenReversed(parseRepository.getTypesFromCategory(TypeCategory.tc10.v())));

        // 路描述词
        cache.setRoadDesc(lenReversed(parseRepository.getTypesFromCategory(TypeCategory.tc6.v())));

        // 解析的目标类型
        cache.setParseTargetTypes(lenReversed(parseRepository.getTypesFromCategory(TypeCategory.tc11.v())));
    }

    private void constructDynamicRegex() {
        Regex.ar1.setRegex(String.join("|", cache.getProvTypes()));
        Regex.ar2.setRegex(String.join("|", cache.getCityTypes()));
        Regex.ar3.setRegex(String.join("|", cache.getDistTypes()));
        Regex.ar4.setRegex(String.join("|", cache.getTownTypes()));
        Regex.ar5.setRegex(String.join("|", cache.getRoadTypes()));
        Regex.ar6.setRegex(String.join("|", cache.getPoiStrTypes()));
        Regex.ar7.setRegex(String.join("|", cache.getRpDetailTypes()));
        Regex.arPt.setRegex(String.join("|", cache.getParseTargetTypes()));
    }

    private List<String> lenReversed(List<String> list) {
        return list.stream().sorted(Comparator.comparingInt(String::length).reversed()).toList();
    }

}
